<?php

namespace App\Http\Controllers\Api;

use App\Handlers\ImageUploadHandler;
use App\Http\Requests\Api\CrowdFundingRequest;
use App\Http\Requests\Api\ShopRoleRequest;
use App\Models\Brand;
use App\Models\Commodity;
use App\Models\CommodityAttr;
use App\Models\CommodityType;
use App\Models\Config;
use App\Models\Deal;
use App\Models\PowerLog;
use App\Models\RentCloth;
use App\Models\RentClothDetail;
use App\Models\RentClothOrder;
use App\Models\Shop;
use App\Models\ShopBrowse;
use App\Models\ShopCom;
use App\Models\ShopCrowd;
use App\Models\ShopRole;
use App\Models\ShopRolePraise;
use App\Models\ShowImage;
use App\Models\User;
use App\Models\UserLabel;
use App\Models\Wallet;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Events\SendNoticeToOne;
use App\Events\SendNoticeToSome;


/**
 * @title 店铺相关
 * @description 接口说明
 */
class ShopController extends ApiController
{
    /**
     * @title 首页
     * @description 接口说明
     * @author cqd
     * @url /api/Shop/index
     * @method POST
     * @module 店铺众筹
     *
     * @return banner:banner图
     * @return platform:平台视频
     * @return show_image:数据@
     * @show_image user_id:用户id hot_spot:热度 nickname:名字 avtar:头像 img_url:圖片地址 id:晒单id
     *
     */
    public function index(Config $config, ShowImage $showImage, User $user, RentClothOrder $RentClothOrder)
    {
        $arr = array();
        $banner = $config->getEClotheBanner();
        $platform = $config->getEClothePlatform();
        $data = $RentClothOrder::take(4)->get(['user_id', 'img_url', 'hot_spot', 'id'])->toArray();
        if ($data) {
            foreach ($data as $key => $value) {
                $user = User::where('id', '=', $value['user_id'])->first();
                // $data[$key]['avatar'] = config('app.url') . '/uploads/' . $user['avatar'];
                $data[$key]['avatar'] = $user['avatar'];
                $data[$key]['nickname'] = $user['nickname'];
                foreach ($value['img_url'] as $key2 => $value2) {
                    $data[$key]['img_url'][$key2] = config('app.url') . '/uploads/' . $value2;
                }
            }
        }

        $return = [
            'banner' => $banner,
            'platform' => $platform,
            'show_image' => $data,
        ];

        return $this->success($return);
    }

    public function crowdFundingList(Request $request, Shop $shop, ShopCrowd $shopcrowd)
    {
        $status = $request->status;
        if (!$status) {
            return $this->failed('缺少参数status');
        }

        $shop_lists = $shop
            ->where('status', $status)
            ->orderBy('crowd_funding_start', 'desc')
            ->with(['shopcrowd'])
            ->get();

        $shop_end = $shop
            ->where([
                ['crowd_funding_end', '<', time()],
                ['status', 1],
            ])
            ->get(); //众筹中，且期限到期
        if (count($shop_end) > 0) {
            $shop_ids = $shop_end->pluck('id');
            $shop_crowds = $shopcrowd->whereIn('shop_id', $shop_ids)->get();

            DB::beginTransaction();
            try {
                $shop->where([
                    ['crowd_funding_end', '<', time()],
                    ['status', 1],
                ])->update(['status' => 4]); //更新状态
                foreach ($shop_crowds as $key => $value) {
                    $this->handleCrowds($value);
                }
                DB::commit();
            } catch (\Exception $exception) {
                DB::rollBack();
            }
        }

        foreach ($shop_lists as $key => $value) {
            $shop_lists[$key] = $value->transform_crowdFunding_list();
        }
        return $this->success($shop_lists);
    }
    /**
     * @title 众筹项目列表(分页)
     * @description status:1众筹中的3众筹完成的shop_type:1线上2线下
     * @author wjx
     * @url /api/Shop/crowdList
     * @method POST
     * @module 店铺众筹
     *
     * @param name:type type:string require:1 default:refresh other: desc:方法参数:more/refresh
     * @param name:offset type:int require:1 default:10 other: desc:方法参数:每页数据量
     * @param name:ID type:int require:1 default:-1 other: desc:数据起点ID
     *
     */
    public function crowdList(Request $request, Shop $shop, ShopCrowd $shopcrowd)
    {
        $startId = $request->ID ? $request->ID : 0;
        $offset = $request->offset ? $request->offset : 10;
        if ($offset > 25) {
            $offset = 25;
        }
        $loadType = $request->type;
        if (!in_array($loadType, ['more', 'refresh'])) {
            return $this->failed('type参数错误');
        }
        if ($loadType == 'more') {
            $shop_lists = $shop
                ->whereIn('status', [1, 3])
                ->filters([['id', '<', $startId]])
                ->take($offset)
                ->orderBy('id', 'desc')
                ->with(['shopcrowd'])
                ->get();
        } else {
            $shop_lists = $shop
                ->whereIn('status', [1, 3])
                ->filters([['id', '>', $startId]])
                ->take($offset)
                ->orderBy('id', 'desc')
                ->with(['shopcrowd'])
                ->get();
        }

        $shop_end = $shop
            ->where([
                ['crowd_funding_end', '<', time()],
                ['status', 1],
            ])
            ->first(); //众筹中，且期限到期

        if ($shop_end) {
            $shop_id = $shop_end->id;
            $user_id = $shop_end->user_id;
            $shop_crowds = $shopcrowd->where('shop_id', $shop_id)->get();
            event(new SendNoticeToSome($shop_crowds,2,2));
            DB::beginTransaction();
            try {
                $shop_end->status = 4;
                $shop_end->save();
                event(new SendNoticeToOne($shop_end,2,4));
                foreach ($shop_crowds as $key => $value) {
                    $this->handleCrowds($value);
                }
                DB::commit();
            } catch (\Exception $exception) {
                DB::rollBack();
            }
        }

        foreach ($shop_lists as $key => $value) {
            $shop_lists[$key] = $value->transform_crowdFunding_list();
        }
        return $this->success($shop_lists);
    }

    public function handleCrowds($value)
    {
        if ($value->is_trust == 2) {
            Wallet::where('user_id', $value->user_id)->increment('money', $value->money);
            Deal::add_log($value->user_id, 0, $value->money, 1, '项目失败，返还认筹金');
        }
    }

    /**
     * @title 我的众筹项目
     * @description 接口描述shop_type:1线上2线下
     * @author wjx
     * @url /api/Shop/my_shop_list
     * @method POST
     * @module 店铺众筹
     * @header name:accessToken require:1 default: desc:用户token
     *
     * @return my_start:我发起的
     * @return my_join:我参与的
     */
    public function my_shop_list(Request $request, Shop $shop, ShopCrowd $shopcrowd)
    {
        $user = $request->user;
        $my_start = $shop->where(['user_id' => $user->id])->where('status','<>',0)->orderBy('id', 'desc')->get();
        
        foreach ($my_start as $key => $value) {
            $my_start[$key] = $value->transform_my_shop_list();
        }
        $my_join = $shopcrowd->where('user_id', $user->id)->with(['shop'])->orderBy('id', 'desc')->get();

        foreach ($my_join as $key => $value) {
            $my_join[$key] = $value->transform_my_join_list();
        }
        return $this->success(compact('my_start', 'my_join'));

    }

    /**
     * @title 发起众筹
     * @description 接口说明
     * @author wjx
     * @url /api/Shop/initiateCrowdFunding
     * @method POST
     * @module 店铺众筹
     * @header name:accessToken require:1 default: desc:用户token
     *@param name:promoter type:string require:1  other: desc:发起人
     *@param name:phone type:string require:1  other: desc:手机号
     *@param name:address type:string require:1  other: desc:店铺地址
     *@param name:wechat type:string require:0  other: desc:微信号
     *@param name:area type:int require:  other: desc:店铺面积
     *@param name:shop_price type:int require:1  other: desc:拟投资金额
     *@param name:label type:string require:1 other: desc:标签(格式：[1,2,3])
     *@param name:shop_info type:string require:1  other: desc:店铺图片(base_64,格式：["1","2","3"])
     *@param name:comment type:string require: other: desc:备注
     *@param name:shop_type type:string require:1 other: desc:1/线上2/线下
     *@param name:step1 type:int require:1 other: desc:500的有几个
     *@param name:step2 type:int require:1 other: desc:1300的有几个
     *@param name:step3 type:int require:1 other: desc:5000的有几个
     */
    public function initiateCrowdFunding(Request $request, CrowdFundingRequest $funddingRequest, ImageUploadHandler $imageUploadHandler)
    {
        $user = $request->user;
        $img = json_decode($funddingRequest->shop_info);
        if (!is_array($img)) {
            return $this->failed('图片参数格式错误');
        }
        $img_arr = [];
        foreach ($img as $v) {
            $save_path = $imageUploadHandler->saveBase64Image($v, 'CrowdFunding', $user->id);

            if ($save_path) {
                $img_arr[] = $save_path['path'];
            } else {
                return $this->failed('图片上传失败');
            }
        }
        if ($funddingRequest->shop_type == 1) {
            $type = '线上';
        } else {
            $type = '线下';
        }
        $shop = new shop();
        $shop->fill($funddingRequest->all());
        $shop->shop_info = $img_arr;
        $shop->shop_name = $funddingRequest->promoter . $type . '的店铺';
        $shop->comment = isset($funddingRequest->comment) ? $funddingRequest->comment : '';
        $shop->status = 0;
        $shop->user_id = $user->id;
        $shop->crowd_funding_start = time();
        $shop->crowd_funding_end = strtotime('+1month');
        if (!is_array(json_decode($funddingRequest->label))) {
            return $this->failed('标签参数格式错误');
        }
        $shop->label = implode(',', json_decode($funddingRequest->label));

        $res = $shop->save();

        if ($res) {
            return $this->message('申请成功,请等待管理员审核');
        } else {
            return $this->failed('申请失败');
        }

    }

    /**
     * @title 店铺角色候选人
     * @description 接口说明 is_praise=1已点赞=2未点赞
     * @author wjx
     * @url /api/Shop/ShopKeeperCandidate
     * @method POST
     * @module 店员竞选
     * @header name:accessToken require:1 default: desc:用户token
     * @param name:role_type type:int require:1 default: other: desc:角色类型1店长2店员3模特
     * @param name:shop_id type:int require:1 default: other: desc:店铺ID
     *
     * @return data:数据@
     * @data user_id:用户id hot_spot:热度 name:名字 avtar:头像
     */
    public function ShopKeeperCandidate(Request $request, User $user)
    {
        $user = $request->user;
        $role_type = $request->role_type;
        $shop_id = $request->shop_id;
        if (!$role_type || !$shop_id) {
            return $this->failed('缺少参数');
        }
        $data = ShopRole::where(['role' => $role_type, 'shop_id' => $shop_id])->with('user')->get();
        $data->transform(function ($item) use ($user) {
            $item->shop_role_id = $item->id;
            $item->is_praise = $this->is_praise($user->id, $item->id);
            $item->avatar = $item->user->avatar;
            $item->name = $item->user->nickname;
            return $item->only(['shop_role_id', 'user_id', 'hot_spot', 'name', 'avatar', 'is_praise']);
        });
        return $this->success($data);
    }

    public function is_praise($user_id, $role_id)
    {

        $data = ShopRolePraise::where([
            ['user_id', $user_id],
            ['role_id', $role_id],
        ])->first();

        if ($data) {
            return 1;
        } else {
            return 2;
        }
    }
    /**
     * @title 店铺角色竞选
     * @description 接口说明
     * @author wjx
     * @url /api/Shop/applyStoreManager
     * @method POST
     * @module 店员竞选
     *
     * @header name:accessToken require:1 default: desc:用户token
     * @param name:role type:int require:1  other: desc:角色类型1店长2店员3模特
     * @param name:shop_id type:int require:1  other: desc:店铺id
     * @param name:name type:string require:1  other: desc:名字
     * @param name:phone type:int require:1 other: desc:手机
     * @param name:address type:string require:1  other: desc:区域
     * @param name:self_introduction type:string require:1  other: desc:自我介绍
     * @param name:img_url type:string require:1  other: desc:竞选图片(base_64(格式：["1","2","3"]))
     * @param name:label type:string require:1  other: desc:个性标签(格式：[1,2,3])
     */
    public function applyStoreManager(Request $request, ShopRoleRequest $shopRolerequest, ImageUploadHandler $imageUploadHandler)
    {
        $user = $request->user;
        $res = ShopRole::where([
            'shop_id' => $shopRolerequest->shop_id,
            'role' => $shopRolerequest->role,
            'user_id' => $user->id,
        ])->with('shop')
            ->first();

        // if ($res->shop->shop_type == 1) {
        //     return $this->failed('线上店铺无法竞选');
        // }
        if ($res) {
            return $this->failed('每个店铺每个角色只能竞选一次');
        }
        $shop_role = new ShopRole();
        $shop_role->fill($shopRolerequest->all());
        $img = json_decode($shopRolerequest->img_url);
        if (!is_array($img)) {
            return $this->failed('图片参数类型错误');
        }
        $arr = array();
        foreach ($img as $k => $v) {
            $save_path = $imageUploadHandler->saveBase64Image($v, 'StoreManager', $user->id);
            if ($save_path) {
                $arr[] = $save_path['path'];
            } else {
                return $this->failed('图片上传失败');
            }
        }
        $shop_role->self_introduction = $shop_role->self_introduction ? $shop_role->self_introduction : '';
        $shop_role->img_url = $arr;
        if (!is_array(json_decode($shopRolerequest->label))) {
            return $this->failed('标签参数类型错误');
        }
        $shop_role->label = implode(',', json_decode($shopRolerequest->label));

        $shop_role->user_id = $user->id;

        $res = $shop_role->save();
        if ($res) {
            return $this->message('申请成功');
        } else {
            return $this->failed('服务器错误');
        }
    }

    /**
     * @title 竞选点赞
     * @description 接口说明
     * @author wjx
     * @url /api/Shop/praise_shop_role
     * @method POST
     * @header name:accessToken require:1 default: desc:用户token
     * @module 店员竞选
     * @param name:shop_role_id type:int require:1 default:1 other: desc:角色id
     * @param name:status type:int require:1 default:0 other: desc:状态（0不变1增加2减少）
     *
     */
    public function praise_shop_role(Request $request)
    {
        $user = $request->user;
        $role_id = $request->shop_role_id;
        if (!$role_id) {
            return $this->failed('role_id');
        }
        $status = $request->status;
        $shop_role = ShopRole::where('id', $role_id)->first();
        switch ($status) {
            case '1':
                $shop_role->hot_spot = $shop_role->hot_spot + 1;
                $shop_role->save();
                $count = ShopRolePraise::where(['role_id' => $role_id, 'user_id' => $user->id])->first();
                if ($count) {
                    return $this->failed('每人只能点赞一次');
                }
                $praise = new ShopRolePraise();
                $praise->role_id = $role_id;
                $praise->user_id = $user->id;
                $praise->save();
                event(new SendNoticeToOne($praise,3,14));
                break;
            case '2':
                $shop_role->hot_spot = $shop_role->hot_spot - 1;
                $shop_role->save();
                ShopRolePraise::where([
                    'role_id' => $role_id,
                    'user_id' => $user->id,
                ])->delete();
                break;
            default:
                # code...
                break;
        }

        return $this->message('成功');
    }
    /**
     * @title 店铺角色详情
     * @description 接口说明
     * @author wjx
     * @url /api/Shop/storeManagerDetails
     * @method POST
     * @module 店员竞选
     * @header name:accessToken require:1 default: desc:用户token
     * @param name:shop_role_id type:int require:1 default:1 other: desc:角色id
     *
     * @return shop_id:店铺id
     * @return hot_spot:热度
     * @return name:名字
     * @return phone:手机
     * @return area:区域
     * @return self_introduction:介绍
     * @return img_url:图片地址
     * @return user_id:用户id
     * @return user_avatar:用户头像
     * @return is_praise:是否点赞
     * @return label:标签
     * @return praise_avatar:点赞人头像
     */
    public function storeManagerDetails(Request $request)
    {
        $user = $request->user;
        $data = ShopRole::where('id', $request->shop_role_id)->with('user')->first();
        if (!$data) {
            return $this->failed('参数错误');
        }
        $data->browse_num = $data->browse_num + 1;
        $data->save();
        $arr = array();
        foreach ($data['img_url'] as $k => $v) {
            $arr[] = config('app.img_url') . $v;
        }
        $detail = [];
        $detail['img_url'] = $arr;
        // $detail['user_avatar'] = config('app.img_url') . $data->user->avatar;
        $detail['user_avatar'] = $data->user->avatar;
        $detail['name'] = $data->user->nickname;
        $detail['created_at'] = $data->created_at->toDateString();
        $detail['hot_spot'] = $data->hot_spot;
        $detail['browse_num'] = $data->browse_num;
        $detail['self_introduction'] = $data->self_introduction;
        $detail['is_praise'] = $this->is_praise($user->id, $data->id);
        $detail['label'] = UserLabel::whereIn('id', explode(',', $data->label))->get()->pluck('name');

        $praise = ShopRolePraise::where('role_id', $request->shop_role_id)->get()->pluck('user_id');
        $praise_avatar = User::whereIn('id', $praise)->get(['id as user_id', 'avatar'])->each(function ($img) {
            $img->avatar = $img->avatar;
        });
        $detail['praise_avatar'] = $praise_avatar;
        return $this->success($detail);
    }

    /**
     * @title 众筹详情
     * @description 接口说明
     * @author wjx
     * @url /api/Shop/crowdFundingDetails
     * @method POST
     * @module 店铺众筹
     * @header name:accessToken require:1 default: desc:用户token
     * @param name:shop_id type:int require:1 default:1 other: desc:店铺id
     * @param name:shop_type type:int require:1 default:1 other: desc:店铺类型1线上2线下
     *
     * @return shop_price:众筹金额
     * @return has_crowd:已筹金额
     * @return promoter:发起人
     * @return address:位置
     * @return longitude:经度
     * @return latitude:纬度
     * @return area:面积
     * @return rest_time:到期时间
     * @return shop_info:店铺图片
     *
     */
    public function crowdFundingDetails(Request $request, Shop $shop, ShopCrowd $shop_crowds)
    {
        $user = $request->user;
        $shop_id = $request->shop_id;
        $shop_type = $request->shop_type;
        if (!$shop_id || !$shop_type) {
            return $this->failed('缺少参数');
        }

        switch ($shop_type) {
            case '1':
                $shop_detail = $shop->where(['id' => $shop_id, 'shop_type' => $shop_type])->with(['shopcrowd', 'user'])->first();
                if (!$shop_detail) {
                    $shop_detail = [];
                    return $this->success($shop_detail);
                }
                $detail = $shop_detail->transform_shop_detail_line();
                break;
            case '2':
                $shop_detail = $shop->where(['id' => $shop_id, 'shop_type' => $shop_type])->with(['shopcrowd', 'user', 'shoprole'])->first();
                if (!$shop_detail) {
                    $shop_detail = [];
                    return $this->success($shop_detail);
                }
                $detail = $shop_detail->transform_shop_detail();
                break;
            default:
                break;
        }
        $shop_count = ShopBrowse::where(['shop_id' => $shop_id, 'user_id' => $user->id])->count();
        if ($shop_count == 0) {
            ShopBrowse::create([
                'user_id' => $user->id,
                'shop_id' => $shop_id,
            ]);
        }

        return $this->success($detail);
    }


    public function returnCloth(Request $request, CommodityAttr $attr, RentCloth $rentcloth)
    {
        $user = $request->user;
        if (!$request->pick_code) {
            return $this->failed('缺少参数pick_code');
        }

        $pick_code = explode(',', $request->pick_code);
        $attr_lists = $attr->whereIn('pick_code', $pick_code)->with(['commodity', 'brand', 'commodityType'])->get();
        if (count($attr_lists) == 0) {
            return $this->failed('没有商品信息');
        }

        $attr_lists->transform(function ($attr_list) {
            $attr_list->brand_name = Brand::where('id', $attr_list->commodity->brand_id)->value('name');
            $attr_list->commodity_img = config('app.img_url') . ($attr_list->commodity->pictures)[0];
            $attr_list->commodity_type = CommodityType::where('id', $attr_list->commodity->commodity_type)->value('name');
            $attr_list->stock_num = $attr_list->stock_num;
            $attr_list->attr_value = $attr_list->attr_value;
            $attr_list->attr_id = $attr_list->id;
            $attr_list->power_price = $attr_list->commodity->power_price;
            return $attr_list->only(['brand_name', 'commodity_img', 'commodity_type', 'stock_num', 'attr_value', 'attr_id', 'power_price']);
        });
        // $total_price = $attr_lists->sum('power_price');
        $rent_time = $rentcloth->where([
            ['user_id', $user->id],
            ['status', 1],
        ])->value('rent_time');
        $rent_time = date('Y-m-d H:i', $rent_time);
        return $this->success(compact('attr_lists', 'rent_time'));

    }


    public function confirmReturnCloth(Request $request, CommodityAttr $attr, Wallet $wallet)
    {

        $user = $request->user;
        $shop_id = $request->shop_id;
        $attr_id = explode(',', $request->attr_id);

        $user_power = $user->wallet->computing_power;
        $res = CommodityAttr::whereIn('id', $attr_id)->get();

        DB::beginTransaction();
        try {
            $res->each(function ($data) use ($shop_id) {
                ShopCom::where(['commodity_attr_id' => $data->id, 'shop_id' => $shop_id])->increment('stock', 1);
                $rent_id = RentClothDetail::where('commodity_id', '=', $data->commodity_id)
                    ->orderBy('id', 'desc')
                    ->value('rent_id');
                RentCloth::where('id', $rent_id)
                    ->update([
                        'back_time' => time(),
                        'status' => 2,
                    ]);
            });
            // Wallet::where('user_id', $user->id)->update([
            //     'computing_power' => $new_power,
            // ]);
            // PowerLog::add_log($user->id, 2, 20, 1);
            DB::commit();
            return $this->message('还衣成功');
        } catch (\Exception $exception) {

            DB::rollBack();
            return $this->failed('还衣失败');
        }
    }
    /**
     * @title 我的租衣
     * @description
     * @author wjx
     * @url /api/Shop/myRentclothPage
     * @method POST
     * @module 还衣相关
     * @header name:accessToken require:1 default: desc:用户token
     *
     *
     */
    public function myRentclothPage(Request $request, RentCloth $rentcloth)
    {
        $user = $request->user;

        $rentcloth = RentCloth::where(['user_id' => $user->id, 'status' => 1])->with('rentclothdetail')->first();
        if (!$rentcloth) {
            return $this->success($rentcloth);
        }

        $rent_time = date('Y-m-d H:i:s', $rentcloth->rent_time);
        $total_power = PowerLog::where([['user_id', $user->id], ['type', 7], ['created_at', '>', $rent_time]])->sum('power');
        // $total_power = PowerLog::where([['user_id', $user->id], ['type', 7], ['rent_id', $rentcloth->id]])->sum('power');

        $rent_id = $rentcloth->id;
        $detail = $rentcloth->rentclothdetail->transform(function ($item) {
            $commodity = Commodity::where('id', $item->commodity_id)->with(['type'])->first();
            $attr = CommodityAttr::where('id', $item->commodity_attr_id)->first();
            $item->commodity_img = config('app.img_url') . ($commodity->pictures)[0];
            $item->commodity_type = $commodity->type->name;
            $item->brand_name = $commodity->commodity_name;
            $item->attr_value = $attr->attr_value ? $attr->attr_value : "L号";

            return $item->only(['brand_name', 'commodity_img', 'commodity_type', 'attr_value']);
        });
        return $this->success(compact('rent_id', 'detail', 'total_power'));
    }
    /**
     * @title 确认还衣页面(扫码)
     * @description total_price=20
     * @author wjx
     * @url /api/Shop/confirmReturnClothPage
     * @method POST
     * @module 还衣相关
     * @header name:accessToken require:1 default: desc:用户token
     *
     * @param  name:rent_id type:string require:1 default: other: desc:租衣ID
     *
     */
    public function confirmReturnClothPage(Request $request, RentCloth $rentcloth)
    {
        $rent_id = $request->rent_id;
        if (!$rent_id) {
            return $this->failed('缺少参数');
        }
        $rentcloth = RentCloth::where(['id' => $rent_id, 'status' => 1])->with('rentclothdetail')->first();

        if (!$rentcloth) {
            return $this->failed('该订单已归还');
        }

        $detail = $rentcloth->rentclothdetail->transform(function ($item) {
            $commodity = Commodity::where('id', $item->commodity_id)->with(['type'])->first();
            $attr = CommodityAttr::where('id', $item->commodity_attr_id)->first();
            $item->commodity_img = config('app.img_url') . ($commodity->pictures)[0];
            $item->commodity_type = $commodity->type->name;
            $item->brand_name = $commodity->commodity_name;
            $item->attr_value = $attr->attr_value ? $attr->attr_value : "L号";
            $item->pick_code = $attr->pick_code;
            $has_bro = RentClothDetail::where('commodity_attr_id', $item->commodity_attr_id)->get();
            $item->rent_num = count($has_bro);
            $user_attr = $has_bro->pluck('user_id');
            $user_avatar = User::whereIn('id', $user_attr)->get(['id as user_id', 'avatar'])->each(function ($img) {
                $img->avatar = $img->avatar;
            });
            $item->rent_user_avatar = $user_avatar;
            return $item->only(['brand_name', 'commodity_img', 'commodity_type', 'attr_value', 'pick_code', 'rent_user_avatar', 'rent_num']);
        });
        return $this->success(compact('rent_id', 'detail'));
    }

    /**
     * @title 确认还衣按钮(新)
     * @description total_price=20
     * @author wjx
     * @url /api/Shop/confirmReturnClothNew
     * @method POST
     * @module 还衣相关
     * @header name:accessToken require:1 default: desc:用户token
     * @param  name:rent_id type:string require:1 default: other: desc:租衣ID
     *
     */
    public function confirmReturnClothNew(Request $request, CommodityAttr $attr, Wallet $wallet)
    {
        $user = $request->user;
        $rent_id = $request->rent_id;
        if (!$rent_id) {
            return $this->failed('缺少参数rent_id');
        }
        
        $rentcloth = RentCloth::where(['id' => $rent_id, 'status' => 1])->with('rentclothdetail')->first();
        if (!$rentcloth) {
            return $this->failed('订单不存在');
        }
        $role = ShopRole::where(['user_id' => $user->id, 'status' => 1,'shop_id'=>$rentcloth->shop_id])->first();     
        $shop = Shop::where(['user_id' => $user->id, 'status' => 3,'id'=>$rentcloth->shop_id])->first();     
        if (!$role && !$shop) {
            return $this->failed('没有还衣权限');
        }
        $shop_id = $rentcloth->shop_id;
        $rentcloth->back_time = time();
        $rentcloth->status = 2;
        DB::beginTransaction();
        try {
            $rentcloth->save();
            foreach ($rentcloth->rentclothdetail as $key => $value) {
                ShopCom::where(['commodity_attr_id' => $value->commodity_attr_id, 'shop_id' => $shop_id, 'is_buy' => 0])->increment('stock', 1);
            }

            DB::commit();
            return $this->message('还衣成功');
        } catch (\Exception $exception) {

            DB::rollBack();
            return $this->failed('还衣失败');
        }
    }
    /**
     * @title 店铺借还记录
     * @description 接口说明 is_back:0已借出1已归还
     * @author wjx
     * @url /api/Shop/shopRentRecord
     * @method POST
     * @module 还衣相关
     *
     *@header name:accessToken require:1 default: desc:用户token
     *
     * @param name:shop_id type:int require:1 default: desc:店铺ID
     * @param name:date_range type:string require:1 default:all desc:(week/month/all)
     * @param name:type type:string require:1 default:refresh other: desc:方法参数:more/refresh
     * @param name:offset type:int require:1 default:10 other: desc:方法参数:每页数据量
     * @param name:ID type:int require:1 default:-1 other: desc:数据起点ID
     *
     */
    public function shopRentRecord(Request $request)
    {
        $date_range = ($request->date_range) ? ($request->date_range) : 'all';
        $shop_id = $request->shop_id;
        if (!$shop_id) {
            return $this->failed('缺少参数');
        }
        if ($date_range == 'week') {
            $between = [Carbon::now()->subweek(1)->timestamp, time()];
        } else if ($date_range == 'month') {
            $between = [Carbon::now()->submonth(1)->timestamp, time()];
        } else {
            $between = ['0', time()];
        }
        // dd($between);
        $startId = $request->ID ? $request->ID : 0;

        $offset = $request->offset ? $request->offset : 10;
        if ($offset > 25) {
            $offset = 25;
        }
        $loadType = $request->type;
        if (!in_array($loadType, ['more', 'refresh'])) {
            return $this->failed('type参数错误');
        }
        if ($loadType == 'more') {
            $rent_list = RentCloth::filters([
                ['shop_id', '=', $shop_id],
                ['type', '<>', 3],
                ['id', '<', $startId],
            ])->whereBetween('rent_time', $between)
                ->take($offset)
                ->with('user')
                ->orderBy('id', 'desc')
                ->get();
        } else {
            $rent_list = RentCloth::filters([
                ['shop_id', '=', $shop_id],
                ['type', '<>', 3],
                ['id', '>', $startId],
            ])->whereBetween('rent_time', $between)
                ->take($offset)
                ->with('user')
                ->orderBy('id', 'desc')
                ->get();
        }

        $rent_list->transform(function ($item) {
            $item->rent_id = $item->id;
            if ($item->user) {
                // $item->user_avatar = config('app.img_url') . $item->user->avatar;
                $item->user_avatar = $item->user->avatar;
                $item->user_nickname = $item->user->nickname;

            } else {
                $item->user_avatar = '';
                $item->user_nickname = '';
            }
            if ($item->status !== 2) {
                $item->is_back = 0;
                $item->status = '已借出';
            } else {
                $item->is_back = 1;
                $item->status = '已归还';
            }
            return [
                'id' => $item->id,
                'rent_id' => $item->rent_id,
                'user_avatar' => $item->user_avatar,
                'user_nickname' => $item->user_nickname,
                'rent_time' => $item->created_at->toDateTimeString(),
                'back_time' => ($item->back_time) ? date('Y-m-d H:i:s', $item->back_time) : '',
                'status' => $item->status,
                'is_back' => $item->is_back,
            ];
        });
        return $this->success($rent_list);
    }
    /**
     * @title 店铺借还详情
     * @description 接口说明:is_back:0已借出1已归还
     * @author wjx
     * @url /api/Shop/shopRentRecordDetail
     * @method POST
     * @module 还衣相关
     *
     * @header name:accessToken require:1 default: desc:用户token
     *
     * @param  name:rent_id type:int require:1 default: desc:店铺ID
     * @return data:数据@
     * @data rent_id:租衣ID rent_time:租借时间 back_time:归还时间 label:算力得失(获得/消耗) power_num:算力值 status:状态 is_back:是否归还 detail:详情@
     * @detail com_img:图片 com_type:类型 com_name:名称 com_attr:属性
     */
    public function shopRentRecordDetail(Request $request)
    {
        $rent_id = $request->rent_id;
        if (!$rent_id) {
            return $this->failed('缺少参数');
        }
        $list = RentClothDetail::where('rent_id', $rent_id)->with(['commodity', 'commodityAttr'])->get();
        $rent_data = RentCloth::where('id', $rent_id)->first();
        $status = $rent_data->status;
        $back_time = $rent_data->back_time;
        $rent_time = $rent_data->rent_time;
        $data = [];
        if ($status !== 2) {
            $is_back = 0;
            $status = '已借出';
            $label = "消耗算力:";
            $power_num = "50";
        } else {
            $is_back = 1;
            $status = '已归还';
            $label = "获得算力:";
            $power_num = $this->get_rent_power($rent_data->user_id, $rent_time);
        }
        $data[0]['rent_time'] = ($rent_time) ? date('Y-m-d H:i:s', $rent_time) : '';
        $data[0]['back_time'] = ($back_time) ? date('Y-m-d H:i:s', $back_time) : '';
        $data[0]['label'] = $label;
        $data[0]['power_num'] = $power_num;
        $data[0]['status'] = $status;
        $data[0]['is_back'] = $is_back;
        $data[0]['detail'] = $list->transform(function ($item) use ($status, $back_time,$rent_time) {
            $item->commodity_type = CommodityType::where('id', $item->commodity->commodity_type)->value('name');
            $item->attr_value = $item->commodityAttr->attr_value;
            
            return [               
                'com_img' => config('app.img_url') . ($item->commodity->pictures)[0],
                'com_name' => $item->commodity->commodity_name,
                'com_type' => $item->commodity_type,
                'com_attr' => $item->attr_value,
            ];
        });


        return $this->success($data);
    }
    /**
     * @title 个人借还记录
     * @description 接口说明: is_back:0已借出1已归还
     * @author wjx
     * @url /api/Shop/rentRecord
     * @method POST
     * @module 还衣相关
     *
     *@header name:accessToken require:1 default: desc:用户token
     *
     * @param name:date_range type:string require:1 default: desc:(week/month/all)
     * @param name:type type:string require:1 default:refresh other: desc:方法参数:more/refresh
     * @param name:offset type:int require:1 default:10 other: desc:方法参数:每页数据量
     * @param name:ID type:int require:1 default:-1 other: desc:数据起点ID
     *
     * @return data:数据@
     * @data rent_id:租衣ID rent_time:租借时间 back_time:归还时间 label:算力得失(获得/消耗) power_num:算力值 status:状态 detail:详情@
     * @detail com_img:图片 com_type:类型 com_name:名称 com_attr:属性
     *
     */
    public function rentRecord(Request $request, CommodityAttr $commodityAttr, Commodity $commodity, RentCloth $rentCloth, Carbon $Carbon)
    {
        $user = $request->user;
        $date_range = $request->date_range;
        if ($date_range == 'week') {
            $between = [Carbon::now()->subweek(1)->timestamp, time()];
        } else if ($date_range == 'month') {
            $between = [Carbon::now()->submonth(1)->timestamp, time()];
        } else {
            $between = ['0', time()];
        }
        $startId = $request->ID ? $request->ID : 0;
        $offset = $request->offset ? $request->offset : 10;
        if ($offset > 25) {
            $offset = 25;
        }
        $loadType = $request->type;
        if (!in_array($loadType, ['more', 'refresh'])) {
            return $this->failed('type参数错误');
        }
        if ($loadType == 'more') {
            $lists = RentCloth::filters([
                ['user_id', '=', $user->id],
                ['type', '=', 2],
                ['id', '<', $startId],
            ])
                ->whereBetween('rent_time', $between)
                ->take($offset)
                ->with('rentclothdetail')
                ->orderBy('id', 'desc')
                ->get();
        } else {
            $lists = RentCloth::filters([
                ['user_id', '=', $user->id],
                ['type', '=', 2],
                ['id', '>', $startId],
            ])
                ->whereBetween('rent_time', $between)
                ->take($offset)
                ->with('rentclothdetail')
                ->orderBy('id', 'desc')
                ->get();
        }

        // if ($lists->isEmpty()) {
        //     return $this->success($lists);
        // }
        $lists->transform(function ($item) use ($user){
            $item->back_time = ($item->back_time) ? date('Y-m-d H:i:s', $item->back_time) : '';
            $item->detail = $item->rentclothdetail->map(function ($value) {
                $commodity = Commodity::where('id', $value->commodity_id)->with(['type'])->first();
                $value->com_img = config('app.img_url') . ($commodity->pictures)[0];
                $value->com_type = $commodity->type->name;
                $value->com_name = $commodity->commodity_name;
                $attr_value = CommodityAttr::where('id', $value->commodity_attr_id)->value('attr_value');
                $value->com_attr = $attr_value ? $attr_value : "L号";
                return $value->only(['com_img', 'com_type', 'com_name', 'com_attr']);
            });
            if ($item->status == 1) {
                $is_back = 0;
                $status = "已借出";
                $label = "消耗算力:";
                $power_num = "50";
            } else {
                $is_back = 1;
                $status = "已归还";
                $label = "获得算力:";
                $power_num = $this->get_rent_power($user->id,$item->rent_time);
            }
            $item->rent_time = $item->created_at->toDateTimeString();
            $item->is_back = $is_back;
            $item->status = $status;
            $item->label = $label;
            $item->power_num = $power_num;
            $item->rent_id = $item->id;
            return $item->only(['id', 'rent_id', 'rent_time', 'back_time', 'detail', 'label', 'power_num', 'status', 'is_back']);
        });

        return $this->success($lists);
    }

    public function get_rent_power($user_id,$rent_time)
    {
        if($rent_time == 0 || $user_id == 0){
            return 0;
        }
        
        $rent_at = date('Y-m-d H:i:s', $rent_time);
        

        $total_power = PowerLog::where([['user_id', $user_id], ['type', 7], ['created_at', '>', $rent_at]])->sum('power');
        
        return $total_power;
    }

}
